﻿namespace GreenIsomer.Data.Entities.Ddl.Console {
	using System;
	using System.IO;
	using System.Reflection;
	using System.Globalization;

	public static class Program {

		static int Main(string[] args) {

			WriteApplicationName();

			string configFile = args != null && args.Length != 0 ? Path.GetFullPath(args[0]) : null;

			if(string.IsNullOrEmpty(configFile)) {
				OutputUsage();
				return 1;
			}

			Settings settings;
			Console.WriteLine("  Loading " + configFile);
			try {
				settings = Settings.Load(configFile);
			} catch(DirectoryNotFoundException) {
				Console.WriteLine("    ERROR: Invalid directory specified for config file.");
				Console.WriteLine();
				return 2;
			} catch(FileNotFoundException) {
				Console.WriteLine("    ERROR: Congifuration file not found.");
				Console.WriteLine();
				return 2;
			} catch(Exception ex) {
				Console.WriteLine("    ERROR: " + ex.Message);
				Console.WriteLine();
				return 3;
			}

			Generator generator = new Generator(settings, Path.GetDirectoryName(configFile));
			generator.Output = Console.Out;

			try {
				generator.Generate();
			} catch(Exception ex) {
				Console.WriteLine("    ERROR: " + ex.Message);
				return 3;
			}

			Console.WriteLine();

			return 0;
		}

		private static void WriteApplicationName() {
			Assembly assembly = Assembly.GetCallingAssembly();

			Version version = assembly.GetName().Version;

			Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "GrIDDL v{0:0}.{1:0}",
				version.Major, version.Minor));
			Console.WriteLine("GreenIsomer.Data.Entities.Ddl Command Line Utility");
			Console.WriteLine();
		}

		private static void OutputUsage() {
			Console.WriteLine("    ERROR: Please specify a configuration file.");
			Console.WriteLine();
			Console.WriteLine("  Usage:");
			Console.WriteLine("     Griddl [configFile]");
			Console.WriteLine();
		}

	}

}